#!/usr/bin/env bash
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2023-10-28 00:01:57
# @LastEditTime: 2023-10-28 01:30:56
# @Description:
###

CURRENT_DIR=$(
    cd "$(dirname "$0")"
    pwd
)

function logger() {
    case "$1" in
    "error" | "red")
        echo -e "\e[1;31m$2\e[0m"
        echo "$2" >>${CURRENT_DIR}/install.log
        exit 1
        ;;
    "warning" | "yellow")
        echo -e "\e[1;33m$2\e[0m"
        echo "$2" >>${CURRENT_DIR}/install.log
        ;;
    "success" | "green")
        echo -e "\e[1;32m$2\e[0m"
        echo "$2" >>${CURRENT_DIR}/install.log
        ;;
    "info" | "blue")
        echo -e "\e[1;34m$2\e[0m"
        echo "$2" >>${CURRENT_DIR}/install.log
        ;;
    esac
}

# 判断是否root用户
if [ $(id -u) -ne 0 ]; then
    logger error "########## This script must be run as root !!! ##########"
fi

# 环境检查
echo "time: $(date)"

if which getenforce && [ $(getenforce) == "Enforcing" ]; then
    logger info "... 关闭 SELINUX"
    setenforce 0
    sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
fi

>${CURRENT_DIR}/install.log
logger info "======================= 开始安装 =======================" 2>&1 | tee -a ${CURRENT_DIR}/install.log

logger info "检查 是否存在离线包 [offline.tar.gz]"
if [ -f ${CURRENT_DIR}/offline.tar.gz ]; then
    tar zxf offline.tar.gz
    chmod +x docker-install.sh && ./docker-install.sh
    logger success "离线docker 安装成功"
    \cp docker-compose /usr/local/sbin/docker-compose
    chmod +x /usr/local/sbin/docker-compose
    logger success "离线ocker-compose 安装成功"
fi

# 检查是否已经安装 Docker
if [ -x "$(command -v docker)" ]; then
    logger info "Docker 已经安装"
else
    # 下载 Docker 二进制安装包
    curl -fsSL https://get.docker.com | sh
    logger success "安装 Docker"
fi

# 检查是否已经安装 Docker Compose
if [ -x "$(command -v docker-compose)" ]; then
    logger info "Docker Compose 已经安装"
else
    # 下载 Docker Compose 二进制安装包
    curl -L https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/sbin/docker-compose
    # 设置可执行权限
    chmod +x /usr/local/sbin/docker-compose
    docker-compose version # 查看docker-compose版本
    logger success "安装 Docker Compose"
fi

# 检查是否有离线镜像
if [ -f ${CURRENT_DIR}/image.tar.gz ]; then
    logger info "检查到离线镜像 [image.tar.gz]"
    cat image.tar.gz | gzip -d | docker load
    logger success "完成镜像恢复"
fi

logger info "开始服务部署 ... [xx.yml]"
